﻿using iSciences.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.ApplicationModel.Search;

// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace iSciences
{
    /// <summary>
    /// A page that displays details for a single item within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class ArticleDetailPage : iSciences.Common.LayoutAwarePage
    {
        public ArticleDetailPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"];
            }

            Article article = (Article)navigationParameter;
            this.DefaultViewModel["Group"] = article.Parent;
            this.DefaultViewModel["Items"] = article.Parent.Articles;
            this.flipView.SelectedItem = article;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            var selectedItem = this.flipView.SelectedItem;
            // TODO: Derive a serializable navigation parameter and assign it to pageState["SelectedItem"]
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //partage
            DataTransferManager.GetForCurrentView().DataRequested += ArticleDetailPage_DataRequested;

        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //delete DataRequested event
            DataTransferManager.GetForCurrentView().DataRequested -= ArticleDetailPage_DataRequested;
        }


        //======================================================
        //Partage
        //======================================================

        void ArticleDetailPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataPackage data = args.Request.Data;
            Article article = (Article)this.flipView.SelectedItem;
            
            //share texete
            data.Properties.Title = article.Title;
            data.SetText(string.Format("{0} {1}",article.Subtitle,article.Url));

            //share image
            var imageSource = RandomAccessStreamReference.CreateFromUri(new Uri(article.ImageUrl));
            data.SetBitmap(imageSource);

            //share data
            data.SetData(article.UniqueId.ToString(), imageSource);

            //share files

            //share url
            data.SetUri(new Uri(article.Url));

        }

        //add to favorite
        private async void Button_Favorite_Click(object sender, RoutedEventArgs e)
        {
            AppData.AddFavorite((Article)this.flipView.SelectedItem);
            MessageDialog msg = new MessageDialog("Article ajouté aux favoris.");
            await msg.ShowAsync();
        }

        private void flipView_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Article article = (Article)this.flipView.SelectedItem;
            this.Frame.Navigate(typeof(WebViewPage), article.Url);   
        }

        private void Button_Home_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(CategoriesPage), AppData.Categories);
        }

        private void MyFavorite_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(FavoritePage));
        }

        private void MySuggestion_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(SuggestionPage));
        }
    }
}
